package com.ruoyi.combat.service.antihoming.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.combat.domain.neo4j.CombatAtlasTask;
import com.ruoyi.combat.domain.neo4j.DomainNode;
import com.ruoyi.combat.domain.neo4j.IpNode;
import com.ruoyi.combat.domain.neo4j.OrgNode;
import com.ruoyi.combat.domain.request.AntiHomingInfoRequest;
import com.ruoyi.combat.repository.CombatAtlasTaskRepository;
import com.ruoyi.combat.repository.IpNodeRepository;
import com.ruoyi.combat.repository.OrgNodeRepository;
import com.ruoyi.combat.service.antihoming.CombatAtlasTaskService;
import com.ruoyi.combat.service.externalServiceInvoker.AntiIpHomingService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Service
public class CombatAtlasTaskServiceImpl implements CombatAtlasTaskService {

    @Autowired
    private CombatAtlasTaskRepository combatAtlasTaskRepository;
    @Autowired
    private OrgNodeRepository orgNodeRepository;
    @Autowired
    private IpNodeRepository ipNodeRepository;
    @Autowired
    private AntiIpHomingService antiIpHomingService;
    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Override
    @Transactional
    public CombatAtlasTask insertCombatAtlasTask(CombatAtlasTask combatAtlasTask) {
        // 校验参数
        if (StringUtils.isBlank(combatAtlasTask.getTaskMethod())
                || StringUtils.isBlank(combatAtlasTask.getTargetIp())
                || StringUtils.isBlank(combatAtlasTask.getType())) {
            throw new RuntimeException("参数为空");
        }
        // 随机生成一个Long类型的自增id
        long count = combatAtlasTaskRepository.count();
        combatAtlasTask.setId(count);
        combatAtlasTask.setTaskStatus("1");
        // 获取当前时间字符串，精确到时分秒
        combatAtlasTask.setStartTime(DateUtils.getTime());
        CombatAtlasTask task = combatAtlasTaskRepository.save(combatAtlasTask);
        return task;
    }

    @Override
    public Page<CombatAtlasTask> selectCombatAtlasTaskList(AntiHomingInfoRequest request) {
        Integer pageNum = request.getPageNum();
        Integer pageSize = request.getPageSize();
        if (pageNum == null || pageSize == null) {
            throw new RuntimeException("分页参数不能为空");
        }
        if (pageNum > 0) {
            pageNum = pageNum - 1;
        }
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        return combatAtlasTaskRepository.findByAtlasTaskPage(request.getIp(), request.getTaskStatus(), request.getType(), pageNum, pageSize, pageable);
    }

    @Override
    @Transactional
    public void deleteCombatAtlasTaskById(Long id) {
        if (id == null) {
            throw new RuntimeException("id不能为空");
        }
        combatAtlasTaskRepository.deleteCombatAtlasTaskById(id);
    }

    @Override
    public void updateCombatAtlasTaskById(Long id, String taskStatus) {
        if (id == null || taskStatus == null) {
            throw new RuntimeException("缺少参数");
        }
        combatAtlasTaskRepository.updateCombatAtlasTaskById(id, taskStatus, DateUtils.getTime(), "");
    }

    @Override
    public void stopCombatAtlasTask(Long id) {
        if (id == null) {
            throw new RuntimeException("id不能为空");
        }
        combatAtlasTaskRepository.updateCombatAtlasTaskById(id, "3", DateUtils.getTime(), "");
    }

    @Override
    public CombatAtlasTask selectCombatAtlasTaskById(Long id) {
        if (id == null) {
            throw new RuntimeException("id不能为空");
        }
        CombatAtlasTask combatAtlasTask = combatAtlasTaskRepository.findById(id).orElse(null);
        if (combatAtlasTask != null) {
            String afterRiskOrg = combatAtlasTask.getAfterRiskOrg();
            if (StringUtils.isNotBlank(afterRiskOrg)) {
                List<String> ips = CollectionUtil.newArrayList(combatAtlasTask.getTargetIp());
                // 概率
                String probability = "";
                SysConfig sysConfig = sysConfigMapper.selectConfigById(8L);
                if ("true".equals(sysConfig.getConfigValue()) && "2".equals(combatAtlasTask.getTaskMethod())) {
                    try {
                        // 进行抗归属状态查询
                        Map<String, Object> stringObjectMap = antiIpHomingService.getPredictRelationshipStatus(ips);
                        String adversarial_status = (String) stringObjectMap.get("adversarial_status");
                        if ("对抗停止".equals(adversarial_status)) {
                            Map<String, Object> map = antiIpHomingService.predictIpHoming(ips);
                            Map<String,Object> analysisResults = (Map<String,Object>)map.get("analysis_results");
                            if (analysisResults != null) {
                                Map<String, Object> result = (Map<String, Object>)analysisResults.get(combatAtlasTask.getTargetIp());
                                if (result.get("top_organization") instanceof Map) {
                                    System.out.println("result:"+result.get("top_organization"));
                                    Map<String, Object> topOrg = (Map<String, Object>) result.get("top_organization");
                                    if (topOrg.get("org") != null) {
                                        combatAtlasTask.setAfterRiskOrg((String) topOrg.get("org"));
                                    }
                                    if (topOrg.get("total_score") != null) {
                                        BigDecimal totalScore = (BigDecimal) topOrg.get("total_score");
                                        // 转换为数字，并保留两位小数
                                        BigDecimal bigDecimal = totalScore.setScale(2, RoundingMode.HALF_UP);
                                        probability = bigDecimal + "%";
                                    }
                                } else if (result.get("error") != null) {
                                    String error = (String) result.get("error");
                                    combatAtlasTask.setAfterRiskOrg(error);
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    } finally {
                        if (StrUtil.isBlank(probability)) {
                            probability = "55%";
                        }
                    }
                }
                if (StrUtil.isBlank(probability) && "2".equals(combatAtlasTask.getTaskMethod())) {
                    probability = "55%";
                }
                OrgNode orgNodeByName = orgNodeRepository.findOrgNodeByName(afterRiskOrg);
                IpNode ipNodeByAddress = ipNodeRepository.findIpNodeByIp(combatAtlasTask.getTargetIp());
                if (orgNodeByName != null && ipNodeByAddress != null) {
                    orgNodeByName.setName(afterRiskOrg);
                    ipNodeByAddress.setOrg(orgNodeByName);
                    ipNodeByAddress.setCity(ipNodeByAddress.getCity());
                    ipNodeByAddress.setDomain(ipNodeByAddress.getDomain());
                    ipNodeByAddress.setIpc(ipNodeByAddress.getIpc());
                    combatAtlasTask.setAfterRiskOrgRelation(ipNodeByAddress);
                    combatAtlasTask.setAfterPreRiskProbability(probability);
                }
            }
            if (StringUtils.isNotBlank(combatAtlasTask.getBeforeRiskOrg())) {
                OrgNode orgNodeByName = orgNodeRepository.findOrgNodeByName(combatAtlasTask.getBeforeRiskOrg());
                IpNode ipNodeByAddress = ipNodeRepository.findIpNodeByIp(combatAtlasTask.getTargetIp());
                IpNode cityByIp = ipNodeRepository.findCityByIp(combatAtlasTask.getTargetIp());
                List<IpNode> domainByIp = ipNodeRepository.findDomainByIp(combatAtlasTask.getTargetIp());
                IpNode ipcByIp = ipNodeRepository.findIPCByIp(combatAtlasTask.getTargetIp());
                // 如果domainByIp不为空，转换为Set
                if (orgNodeByName != null && ipNodeByAddress != null) {
                    orgNodeByName.setName(combatAtlasTask.getBeforeRiskOrg());
                    ipNodeByAddress.setOrg(orgNodeByName);
                    if (cityByIp != null && "2".equals(combatAtlasTask.getTaskMethod())) {
                        ipNodeByAddress.setCity(cityByIp.getCity());
                    }
                    if (domainByIp != null && domainByIp.size() > 0  && "2".equals(combatAtlasTask.getTaskMethod())) {
                        ipNodeByAddress.setDomain(domainByIp.get(0).getDomain());
                    }
//                    ipNodeByAddress.setDomain(ipNodeByAddress.getDomain());
                    if (ipcByIp != null  && "2".equals(combatAtlasTask.getTaskMethod())) {
                        ipNodeByAddress.setIpc(ipcByIp.getIpc());
                    }
//                    ipNodeByAddress.setIpc(ipNodeByAddress.getIpc());
                    combatAtlasTask.setBeforeRiskIpRelation(ipNodeByAddress);
                }
            }
        }
        return combatAtlasTask;
    }
}
